//
//  ShopInitDate.m
//  stone-story
//
//  Created by liu dodo on 12-9-27.
//  Copyright (c) 2012年 liu dodo. All rights reserved.
//

#import "ShopInitDate.h"

@interface ShopInitDate ()

@end

@implementation ShopInitDate

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
}

- (void)viewDidAppear:(BOOL)animated
{
    if(!haveConnect)
    {
        [self requestSend];
    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}



#pragma mark 数据请求
- (void)requestSend
{
    //[self HUD_Create:self.view];
   // [self HUD_Show];
    [self setRootNodeName:@"shop"];
    [self request_Send:ShopsAPI withPostArg:nil];
    
}

//调用父类请求[成功]时的方法
- (void)getResultArraySuccess //请求回来并解释好的数据都放在[resultArray]这个数组中,直接引用
{
   // [self HUD_Hide];
    haveConnect=YES;
    NSLog(@"[result count is aaa := %d]",resultArray.count);
    
    
    lf=[[LCFileManager alloc]init];
    lf.delegate=self;
 
    for (NSMutableDictionary* dict in resultArray)
    {
        NSArray *urlArray=[[dict objectForKey:@"shop_photos"] componentsSeparatedByString:@","];
        
        [lf downLoadFilesWithUrlArray:urlArray UIProgressView:nil queueIdentifier:[dict objectForKey:@"shop_code"]saveToPath:@"Documents/shops/" folderName:[dict objectForKey:@"shop_code"]];
    }
    for (NSMutableDictionary* dict in resultArray)
    {
      
        
        NSArray *urlArray=[NSArray arrayWithObjects:[dict objectForKey:@"shop_smalllogo"],[dict objectForKey:@"shop_logo"], nil];
        
        [lf downLoadFilesWithUrlArray:urlArray UIProgressView:nil queueIdentifier:[dict objectForKey:@"shop_code"]
                           saveToPath:[@"Documents/shops/" stringByAppendingString:[dict objectForKey:@"shop_code"]]  folderName:@"logos"];
    }
    
    [self DataInsertToDB];
   
    
}
//调用父类请求[失败]时的方法
- (void)requestError
{
    NSLog(@"发送请求失败");
   // [self HUD_Hide];
}

#pragma mark - 图片下载完成代理方法
-(void)queueFilish:(NSString *)queueIdentifier
{
    NSLog(@"the queue indetifier is:%@",queueIdentifier);
}



#pragma mark - 数据库操作
//数据入库操作
-(void)DataInsertToDB
{
    [self FMDB_OPEN];//打开数据
    [self createTable];//创建表
    [self deleteRecord];//清空表数据
     //插入数据
    for (NSMutableDictionary* dict in resultArray) {
        
        if([self isExistTable:@"tb_shops" InTheDateBase:db]){
            
              NSString *shop_photospath=[@"Documents/shops/" stringByAppendingPathComponent:[dict objectForKey:@"shop_code"]];
            [db executeUpdate:@"INSERT INTO tb_shops VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[dict objectForKey:@"shop_code"],[dict objectForKey:@"shop_name"],[dict objectForKey:@"shop_info"],[dict objectForKey:@"shop_level"],[dict objectForKey:@"shop_logo"],[dict objectForKey:@"shop_smalllogo"],[dict objectForKey:@"shop_linkman"],[dict objectForKey:@"shop_tel"],[dict objectForKey:@"shop_email"],[dict objectForKey:@"shop_addr"],[dict objectForKey:@"shop_note"],[dict objectForKey:@"shop_type"],[dict objectForKey:@"shop_owner"],[dict objectForKey:@"shop_city"],[dict objectForKey:@"shop_province"],[dict objectForKey:@"shop_area"],[shop_photospath stringByAppendingString:@"/"]];
            
        }
        else {
            NSLog(@"table db.Products have not exist!");
        }
        
    }
    
    [self queryTable];

}




//创建或打开数据库
- (void)FMDB_OPEN//1
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDirectory = [paths objectAtIndex:0];
    
    //dbPath： 数据库路径，在Document中。
    NSString *dbPath = [documentDirectory stringByAppendingPathComponent:@"db_stoneStory.db"];
    
    //创建数据库实例 db  这里说明下:如果路径中不存在"Test.db"的文件,sqlite会自动创建"Test.db"
    db= [FMDatabase databaseWithPath:dbPath];
    if (![db open]) {
        NSLog(@"Could not open db.");
        return ;
    }
    else {
        NSLog(@"open db. success!");
    }
    
    
    
}
//创建表
- (void)createTable
{
    //创建一个名为User的表，四个字段 书的ID,书的图片文件名,书的pdf文件名,书的排号
    if(![self isExistTable:@"tb_shops" InTheDateBase:db])
        [db executeUpdate:@"CREATE TABLE tb_shops (shop_code text,shop_name text,shop_info text,shop_level text,shop_logo text,shop_smalllogo text,shop_linkman text,shop_tel text,shop_email text,shop_addr text,shop_note text,shop_type text,shop_owner text,shop_city text,shop_province text,shop_area text,shop_photos_path text)"];
    else {
        NSLog(@"table tb_shops have exist!");
    }
}


//删除数据
- (void)deleteRecord
{
    if([self isExistTable:@"tb_shops" InTheDateBase:db])
    {
        [db executeUpdate:@"DELETE FROM tb_shops "];
    }
    else
    {
        NSLog(@"table tb_shops have not exist!");
    }
}


//查询
- (void)queryTable
{
    //返回数据库中第一条满足条件的结果
    //   NSString *aa=[db stringForQuery:@"SELECT Name FROM User WHERE Age = ?",@"20"];
    
    //返回全部查询结果
    FMResultSet *rs=[db executeQuery:@"SELECT * FROM tb_shops"];
    
    //rs=[db executeQuery:@"SELECT * FROM User WHERE Age = ?",@"20"];
    int columns= [rs columnCount];
    while ([rs next])
    {
       // NSLog(@"\n categroy_id:%@ \n categro_image:%@ \n  parentcategory_id:%@ \n note:%@ \n ",[rs stringForColumn:@"categroy_id"],[rs stringForColumn:@"categroy_name"],[rs stringForColumn:@"parentcategory_id"],[rs stringForColumn:@"note"]);
        for (int i=0; i<columns; i++)
        {
            NSLog(@"the %@ is :%@",[rs columnNameForIndex:i],[rs stringForColumnIndex:i]);
           
        }
        
       
    }
    [rs close];
    [db close];
}

//判断是否存在该表
-(BOOL)isExistTable:(NSString*)tablename InTheDateBase:(FMDatabase *)tdb {
    
    FMResultSet *rs = [tdb executeQuery:@"select count(*) as 'count' from sqlite_master where type ='table' and name = ?", tablename];
    while ([rs next])
    {
        // just print out what we've got in a number of formats.
        NSInteger count = [rs intForColumn:@"count"];
        NSLog(@"isTableOK %d", count);
        
        if (0 == count)
        {
            return NO;
        }
        else
        {
            return YES;
        }
    }
    
    return NO;
}




@end
